﻿using System;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Windows.Forms;
using Av.Utils;
using System.Text;
using System.Xml;
using System.Collections.Generic;
using System.Xml.XPath;
using System.Net;
using System.Collections.Specialized;

namespace JrcUtils
{
    public partial class Form1 : Form
    {

        /// <summary>
        /// To sync w/ ITTC server
        /// </summary>
        IttcCommunicator m_communicator = new IttcCommunicator();

        /// <summary>
        /// Contains list of parsed trades from XML file
        /// </summary>
        List<TradestationLine> m_arTrades = new List<TradestationLine>();

        /// <summary>
        /// Systray icon
        /// </summary>
        protected NotifyIcon m_icon = null;

        #region " Get/set text methods (invoked) "

        delegate void SetTextDelegate(string name, string value);
        delegate string GetTextDelegate(string name);

        /// <summary>
        /// Returns text of control.
        /// </summary>
        /// <param name="name">Name of control</param>
        /// <returns>Text of control. Returns "checked"/"" or "" for CheckBox</returns>
        private string GetText(string name)
        {
            string s = "";

            try
            {
                if(this.InvokeRequired)
                {
                    this.Invoke(new GetTextDelegate(GetText), name);
                } else
                {
                    Control[] ar = this.Controls.Find(name, false);
                    if((ar != null) && (ar.Length > 0))
                    {
                        if(ar[0].GetType() == typeof(CheckBox))
                        {
                            s = ((CheckBox)ar[0]).Checked ? "checked" : "";
                        } else
                        {
                            s = ar[0].Text;
                        }
                    }
                }
            } catch(Exception ex)
            {
            }

            return s;
        }

        /// <summary>
        /// Thread safe AddText
        /// </summary>
        /// <param name="name">Name of control to add text</param>
        /// <param name="value">Text to add</param>
        private void AddText(string name, string value)
        {
            try
            {
                if(this.InvokeRequired)
                {
                    this.Invoke(new SetTextDelegate(AddText), name, value);
                } else
                {
                    Control[] ar = this.Controls.Find(name, false);
                    if((ar != null) && (ar.Length > 0))
                    {
                        ar[0].Text += value;
                        if(ar[0].GetType() == typeof(TextBox))
                        {
                            ((TextBox)ar[0]).SelectionStart = Int32.MaxValue;
                        }
                    }
                }
            } catch(Exception)
            {
            }
        }

        /// <summary>
        /// Thread safe SetText
        /// </summary>
        /// <param name="name">Name of control to set text</param>
        /// <param name="value">Text to set</param>
        private void SetText(string name, string value)
        {
            try
            {
                if(this.InvokeRequired)
                {
                    this.Invoke(new SetTextDelegate(SetText), name, value);
                } else
                {
                    Control[] ar = this.Controls.Find(name, false);
                    if((ar != null) && (ar.Length > 0))
                    {
                        ar[0].Text = value;
                    }
                }

            } catch(Exception ex)
            {
            }
        }

        #endregion

        public Form1()
        {
            InitializeComponent();

            m_communicator.StatusChanged += new StatusChangedHandler(OnDjangoCommunicatorStatusChanged);

        }

        private void OnFormClosed(object sender, FormClosedEventArgs e)
        {
            if(m_icon != null)
            {
                m_icon.Dispose();
            }
        }

        private void OnFormLoad(object sender, EventArgs e)
        {
            try
            {
                Log4cs.Log("Starting {0} (v{1})...", Settings.Name, Settings.Version);

                // In case we need only one instance of program
                EnsureSingleApplication();

                this.Text = Settings.NameVersion;

                CreateTrayIcon();

                // Create context menu for tray icon
                MenuItem[] arMenu = this.CreateMenuItems();
                if(arMenu != null)
                {
                    m_icon.ContextMenu = new ContextMenu(arMenu);
                }

                ReloadSettings();

            } catch(ApplicationException ex)
            {
                MessageBox.Show(ex.ToString(), string.Format("{0} (v{1})", Settings.Name, Settings.Version), MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.Close();
            } catch(Exception ex)
            {
                Log4cs.Log(Importance.Error, "Error loading main form!");
                Log4cs.Log(Importance.Debug, ex.ToString());
                MessageBox.Show("Error loading application!", string.Format("{0} (v{1})", Settings.Name, Settings.Version), MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.Close();
            }
        }

        /// <summary>
        /// Creates tray icon from embedded to project icon. Throws execptions
        /// </summary>
        private void CreateTrayIcon()
        {
            // Create tray icon
            Assembly asm = Assembly.GetExecutingAssembly();
            FileInfo fi = new FileInfo(asm.GetName().Name);
            using(Stream s = asm.GetManifestResourceStream(string.Format("{0}.av1.ico", fi.Name)))
            {
                m_icon = new NotifyIcon();
                m_icon.Visible = true;
                m_icon.Icon = new Icon(s);
            }
        }

        /// <summary>
        /// Ensures that application is the only. Throws ApplicationException if there is such application
        /// </summary>
        private void EnsureSingleApplication()
        {
            bool createdNew = false;
            Mutex mx = new Mutex(false, Settings.Name, out createdNew);
            Log4cs.Log(Importance.Debug, "Is mutex created: {0}", createdNew);

            // If application is already running
            if(createdNew == false)
            {
                throw new ApplicationException(Settings.Name + " application is already running!");
            }
        }


        #region " Context menu methods "

        /// <summary>
        /// Creates context menu for tray icon
        /// </summary>
        /// <returns></returns>
        private MenuItem[] CreateMenuItems()
        {
            MenuItem[] arMenu = null;

            try
            {
                // Got quantity of menus
                arMenu = new MenuItem[MyMenu.Size];

                for(int i = 0; i < MyMenu.Size; i++)
                {
                    arMenu[i] = new MenuItem(MyMenu.ToName(i), OnContextMenuClicked);
                }

                // By default status thread is stopped, so disable "Stop" command
                //arMenu[MyMenu.Position.Stop].Enabled = false;

                // Format "Version"
                arMenu[MyMenu.Position.Version].Text = string.Format("{0} (v{1})", Settings.Name, Settings.Version);

            } catch(Exception ex)
            {
                Log4cs.Log(Importance.Error, "Error creating menu items!");
                Log4cs.Log(Importance.Debug, ex.ToString());
            }

            return arMenu;
        }

        /// <summary>
        /// Handles clicks on systray icon menu
        /// </summary>
        void OnContextMenuClicked(object sender, EventArgs e)
        {
            try
            {
                switch(((MenuItem)sender).Index)
                {
                    //case MyMenu.Position.Start:
                    //    m_icon.ContextMenu.MenuItems[MyMenu.Position.Start].Enabled = false;
                    //    m_icon.ContextMenu.MenuItems[MyMenu.Position.Stop].Enabled = true;
                    //    OnStartStopClicked(null, null);
                    //    break;
                    //case MyMenu.Position.Stop:
                    //    m_icon.ContextMenu.MenuItems[MyMenu.Position.Start].Enabled = true;
                    //    m_icon.ContextMenu.MenuItems[MyMenu.Position.Stop].Enabled = false;
                    //    OnStartStopClicked(null, null);
                    //    break;
                    case MyMenu.Position.Version:
                        MessageBox.Show("JrcUtils by mr. Aleksej Vasinov", Settings.NameVersion, MessageBoxButtons.OK, MessageBoxIcon.Information);
                        break;
                    //case MyMenu.Position.Reload:
                    //    ReloadSettings();
                    //    break;
                    default:
                        this.Close();
                        break;
                }

            } catch(Exception ex)
            {
                Log4cs.Log(Importance.Error, "Error handling context menu click!");
                Log4cs.Log(Importance.Debug, ex.ToString());
            }
        }


        /// <summary>
        /// Reloads setting. Stops thread if necessary
        /// </summary>
        private void ReloadSettings()
        {
            Log4cs.Log("Reloading settings...");
            Settings.Load();

            Debug("Loading information from ITTC server...");
            IttcConnection con = new IttcConnection();
            con.Url = "http://127.0.0.1:10779/get/csts/";
            m_communicator.DownloadCsts(con);
            Debug("Information is loaded");
        }

        /// <summary>
        /// Starts/stops application if needed :)
        /// </summary>
        private void OnStartStopClicked(object sender, object e)
        {
            Log4cs.Log("Start/stop is clicked...");
        }

        #endregion

        private void OnChooseFileButtonClicked(object sender, EventArgs e)
        {
            try
            {
                Button btn = (Button)sender;
                // Where to write selected name
                TextBox txtToSet = txtXmlFilename;
                OpenFileDialog dlg = new OpenFileDialog();

                switch(btn.Name)
                {
                    case "btnChooseUploadFile":
                        dlg.Filter = "CSV files (*.csv)|*.csv|All files (*.*)|*.*";
                        txtToSet = txtUploadFileName;
                        break;
                    default:
                        dlg.Filter = "XML files (*.xml)|*.xml|All files (*.*)|*.*";
                        break;
                }
                if(dlg.ShowDialog() == DialogResult.OK)
                {
                    txtToSet.Text = dlg.FileName;
                    Debug("Selected file is {0}", dlg.FileName);
                }
            } catch(Exception ex)
            {
                Log4cs.Log(Importance.Error, "Error choosing file!");
                Log4cs.Log(Importance.Debug, ex.ToString());
                Debug(Importance.Error, "Error choosing file!");
            }
        }

        private void OnXmlFileParseClicked(object sender, EventArgs e)
        {
            try
            {
                string xmlFile = txtXmlFilename.Text;
                string currencyFrom = "";
                string currencyTo = "";
                int total = 0;
                int tlId = 1;

                Debug("Parsing XML file: {0}...", xmlFile);
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(xmlFile);

                // Clear old trades
                m_arTrades = new List<TradestationLine>();

                Dictionary<string, StringBuilder> ar = new Dictionary<string, StringBuilder>();

                XmlNode currencyNode = xmlDoc.SelectSingleNode("/SystemMarket/SystemInfo/SysInfo/Symbol");
                Log4cs.Log("Currency: {0}", currencyNode.FirstChild.Value);
                currencyFrom = currencyNode.FirstChild.Value.Substring(0, 3);
                currencyTo = currencyNode.FirstChild.Value.Substring(3);
                Log4cs.Log("Tradestation list currencies pair: {0} -> {1}...", currencyFrom, currencyTo);
                Debug("Tradestation currencies: {0} -> {1}...", currencyFrom, currencyTo);

                foreach(XmlNode mainNode in xmlDoc.DocumentElement.ChildNodes)
                {
                    Log4cs.Log(Importance.Debug, "Main node: {0}", mainNode.Name);
                    switch(mainNode.Name.ToLower())
                    {
                        case "trades":
                            TradestationLine tl = new TradestationLine();
                            /* Parsing: <Trades>
                                          <Trade>...</Trade>
                                          ...
                                          <Trade>...</Trade>
                                        </Trades>
                             */
                            if( mainNode.HasChildNodes && mainNode.FirstChild.HasChildNodes )
                            {
                                foreach(XmlNode tradeNode in mainNode.ChildNodes)
                                {
                                    Log4cs.Log("Trade node: {0}", tradeNode.Name);
                                    tl = TradestationLine.ParseXmlNode(tradeNode);
                                    if(total % 2 == 0)
                                    {
                                        tl.Id = tlId;
                                        tlId++;
                                    }
                                
                                    m_arTrades.Add(tl);
                                    total++;

                                }  // END FOREACH ( list all trades )
                            }
                            break;
                        default:
                            break;
                    }

                }  // END FOREACH ( main XML nodes - SystemInformatin, Trades, Rollovers, etc... )

                //foreach( KeyValuePair<string, StringBuilder> kvp in ar )
                //{
                //    Log4cs.Log("{1}{0}{2}", Environment.NewLine, kvp.Key, kvp.Value.ToString());
                //}

                total = m_arTrades.Count;
                Debug("{0} records were parsed from XML file...", total);

            } catch(Exception ex)
            {
                Log4cs.Log(Importance.Error, "Error parsing XML file!");
                Log4cs.Log(Importance.Debug, ex.ToString());
                Debug(Importance.Error, "Error parsing XML file!");
            }
        }

        protected void Debug(string msg, params object[] args)
        {
            Debug(Importance.Info, msg, args);
        }

        protected void Debug(Importance level, string msg, params object[] args)
        {
            StringBuilder sb = new StringBuilder();
            if( level != Importance.No )
            {
                sb.AppendFormat("[{0}] ", level.ToString().ToUpper());
            }

            sb.AppendFormat(msg, args);
            sb.AppendLine();
            this.AddText("txtOutput", sb.ToString());
            txtOutput.SelectionStart = int.MaxValue;
            txtOutput.ScrollToCaret();
        }

        private void ExportTradesToCsv(List<TradestationLine> arTrades, string outputFilename)
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                foreach(TradestationLine tl in arTrades)
                {
                    sb.AppendLine(tl.ToCsv());
                }

                if(MessageBox.Show("Copy to clipboard?", Settings.NameVersion, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    Debug("Copying CSV content to clipboard (press Ctrl+V to insert in some file)");
                    Clipboard.SetText(sb.ToString());
                }
                File.WriteAllText(outputFilename, sb.ToString());
                Debug("{0} file is saved...", outputFilename);
            } catch(Exception ex)
            {
                Log4cs.Log(Importance.Error, "Error exporting list of trades to CSV!");
                Log4cs.Log(Importance.Debug, ex.ToString());
            }
        }

        private void OnExportToCvsClicked(object sender, EventArgs e)
        {
            try
            {
                FileInfo fi = new FileInfo(txtXmlFilename.Text);
                string csvFilename = string.Format("{0}\\{1}.csv", fi.DirectoryName, fi.Name.Substring(0, fi.Name.Length - fi.Extension.Length));
                Log4cs.Log("Exporting to: {0}", csvFilename);
                if( File.Exists(csvFilename) && ( MessageBox.Show("Overwrite file?!", Settings.NameVersion, MessageBoxButtons.YesNo, MessageBoxIcon.Warning) != DialogResult.Yes ) )
                {
                    Log4cs.Log(Importance.Error, "Could not export to {0}, such file exists!", csvFilename);
                    Debug(Importance.Error, "Could not export to {0}, such file exists!", csvFilename);
                } else
                {
                    Log4cs.Log("Saving list of trades to CSV file: {0}...", csvFilename);
                    Debug("Saving list of trades to CSV file: {0}...", csvFilename);
                    ExportTradesToCsv(m_arTrades, csvFilename);

                }
            } catch(Exception ex)
            {
                Log4cs.Log(Importance.Error, "Error exporting to CSV file!");
                Log4cs.Log(Importance.Debug, ex.ToString());
                Debug(Importance.Error, "Error exporting to CSV file!");
            }
        }

        private void OnExamineSysInfoButtonClicked(object sender, EventArgs e)
        {
            try
            {
                string xmlFile = txtXmlFilename.Text;
                TradestationSystemInfo sysInfo = new TradestationSystemInfo();

                Debug("Parsing SysInfo for XML file: {0}...", xmlFile);
                XPathDocument xDoc = new XPathDocument(xmlFile);
                XPathNavigator xNavigator = xDoc.CreateNavigator();
                XPathNodeIterator iterator = xNavigator.Select("/SystemMarket/SystemInfo/SysInfo");
                Log4cs.Log("Got {0} records in SysInfo...", iterator.Count);
                if(iterator.MoveNext())
                {
                    //Log4cs.Log("  {0}", iterator.Current.SelectChildren("", ""));
                    XPathNodeIterator children = iterator.Current.SelectChildren("", "");
                    Log4cs.Log("Children of SysInfo: {0}", children.Count);
                    while(children.MoveNext())
                    {
                        //Log4cs.Log("  {0}", children.Current.Name);
                        switch(children.Current.Name)
                        {
                            case "WindowHandle":
                                sysInfo.WindowHandle = children.Current.Value;
                                break;
                            case "WorkspaceName":
                                sysInfo.WorkspaceName = children.Current.Value;
                                break;
                            case "WindowID":
                                sysInfo.WindowID = children.Current.Value;
                                break;
                            case "System":
                                sysInfo.System = children.Current.Value;
                                break;
                            case "Commission":
                                sysInfo.Commission = children.Current.Value;
                                break;
                            case "Slippage":
                                sysInfo.Slippage = children.Current.Value;
                                break;
                            case "PointValue":
                                sysInfo.PointValue = children.Current.Value;
                                break;
                            case "PriceConversion":
                                sysInfo.PriceConversion = children.Current.Value;
                                break;
                            case "Margin":
                                sysInfo.Margin = children.Current.Value;
                                break;
                            case "Symbol":
                                sysInfo.Symbol = children.Current.Value;
                                break;
                            case "Description":
                                sysInfo.Description = children.Current.Value;
                                break;
                            case "Compression":
                                sysInfo.Compression = children.Current.Value;
                                break;
                            case "VersionType":
                                sysInfo.VersionType = children.Current.Value;
                                break;
                            case "PerUnitCommission":
                                sysInfo.PerUnitCommission = children.Current.Value;
                                break;
                            case "PerUnitSlippage":
                                sysInfo.PerUnitSlippage = children.Current.Value;
                                break;
                            case "InitialCapital":
                                sysInfo.InitialCapital = children.Current.Value;
                                break;
                            case "InterestRate":
                                sysInfo.InterestRate = children.Current.Value;
                                break;
                            case "AccountLocaleID":
                                sysInfo.AccountLocaleID = children.Current.Value;
                                break;
                            case "CounterCurrencyLocaleID":
                                sysInfo.CounterCurrencyLocaleID = children.Current.Value;
                                break;
                            case "BaseCurrencyLocaleID":
                                sysInfo.BaseCurrencyLocaleID = children.Current.Value;
                                break;
                            case "AccountLotSize":
                                sysInfo.AccountLotSize = children.Current.Value;
                                break;
                            case "Input1":
                                sysInfo.InputOne = children.Current.Value;
                                break;
                            case "Input2":
                                sysInfo.InputTwo = children.Current.Value;
                                break;
                            default:
                                Log4cs.Log(Importance.Warning, "Do NOT handle SysInfo.{0} [{1}]!", children.Current.Name, children.Current.Value);
                                break;
                        }
                    }  // END WHILE ( list all properties for SysInfo )

                    Debug(Importance.No, "SysInfo for {1}{0}{2}", Environment.NewLine, xmlFile, sysInfo.ToString());
                    //MessageBox.Show(sysInfo.ToString(), Settings.NameVersion, MessageBoxButtons.OK, MessageBoxIcon.Information);

                }

                //XmlDocument xmlDoc = new XmlDocument();
                //xmlDoc.Load(xmlFile);
            } catch(Exception ex)
            {
                Log4cs.Log(Importance.Error, "Error parsing SystemInfo of Tradestation!");
                Log4cs.Log(Importance.Debug, ex.ToString());
                Debug(Importance.Error, "Error parsing SystemInfo of Tradestation!");
            }
        }

        private void OnUploadFileClicked(object sender, EventArgs e)
        {
            try
            {
                string urlToSend = string.Format("{0}:{1}/test/uploadsignals/3/", Settings.IttcHostname, Settings.IttcPort);
                WebClient wc = new WebClient();
                string s = wc.DownloadString(urlToSend);
                Log4cs.Log(Importance.Debug, s);

                string csrfToken = Common.GetCsrfToken(s);
                Log4cs.Log("Got CSRF token: {0}...", csrfToken);
                NameValueCollection f = new NameValueCollection();
                f.Add("csrfmiddlewaretoken", csrfToken);
                wc.Headers.Add(HttpRequestHeader.Cookie, "csrftoken=" + csrfToken);

                byte[] ba = wc.UploadValues(urlToSend, f);

                //byte[] ba = wc.UploadFile(postUrl, filename);
                if(ba != null)
                {
                    Log4cs.Log("Got response:{0}{1}", Environment.NewLine, Encoding.UTF8.GetString(ba));
                }

                //string filename = txtUploadFileName.Text;
                //KeyValuePair<int, string> kvp = (KeyValuePair<int, string>)lstCsts.SelectedItem;
                //Debug("Uploading file {0} to CST \"{1}\"...", filename, kvp.Value);
                //string postUrl = string.Format("http://127.0.0.1:10779/post/tradesto/{0}/", kvp.Key);

                //Log4cs.Log("Uploading {0} to {1}...", filename, postUrl);
                //WebClient wc = new WebClient();
                //string s = wc.DownloadString(postUrl);
                //Log4cs.Log(Importance.Debug, s);

                //string csrfToken = Common.GetCsrfToken(s);

                ////postUrl += csrfToken + "/";
                //NameValueCollection f = new NameValueCollection();
                //f.Add("csrfmiddlewaretoken", csrfToken);
                //byte[] ba = wc.UploadValues(postUrl, f);
                ////byte[] ba = wc.UploadFile(postUrl, filename);
                //if(ba != null)
                //{
                //    Log4cs.Log("Got response:{0}{1}", Environment.NewLine, Encoding.UTF8.GetString(ba));
                //}

                Debug("File is uploaded!");
            } catch(Exception ex)
            {
                Log4cs.Log(Importance.Error, "Error uploading file!");
                Log4cs.Log(Importance.Debug, ex.ToString());
                Debug(Importance.Error, "Error uploading file!");
            }
        }

        private void OnTestButtonClicked(object sender, EventArgs e)
        {
            try
            {
                WebClient wc = new WebClient();
                StreamWriter sw = null;
                StreamReader sr = null;
                string s = "Content-Type: multipart/form-data; boundary=---------------------------288695814700\nContent-Length: 184\n\n-----------------------------288695814700\nContent-Disposition: form-data; name=\"csrfmiddlewaretoken\"\n36eca0ad3d84765b70021ff2b840df81\n-----------------------------288695814700--";
                string postL = "Content-Type: multipart/form-data; boundary=---------------------------288695814700\nContent-Length: 184\n\n-----------------------------288695814700\nContent-Disposition: form-data; name=\"csrfmiddlewaretoken\"\n{0}\n-----------------------------288695814700--";
                string csrf = "157986c75cc9f86e54870180794582bd";
                NameValueCollection data = new NameValueCollection();
                byte[] ba = null;

                data.Add("xxx", "yyy");
                ba = wc.UploadValues("http://127.0.0.1:10779/post/tradesto/2/", data);
                if( ba != null )
                {
                    Log4cs.Log("Got {0} bytes...", ba.Length);
                    Log4cs.Log(Encoding.UTF8.GetString(ba));
                }

                throw new Exception("STOP IT!!!");

                Log4cs.Log(Importance.Debug, "Sending:{0}{1}", Environment.NewLine, s);
                HttpWebRequest rq = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:10779/post/tradesto/2/");

                //sr = new StreamReader(rq.GetResponse().GetResponseStream());
                //string html = sr.ReadToEnd();
                //Log4cs.Log(html);
                //csrf = Common.GetCsrfToken(html);
                //Log4cs.Log("CSRF token: {0}", csrf);

                //for(int i = 0; i < rq.CookieContainer.Count; i++)
                //{
                //    Log4cs.Log(rq.CookieContainer.ToString());
                //}

                rq = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:10779/post/tradesto/2/");
                rq.Method = "POST";
                rq.ContentType = "multipart/form-data";
                rq.ContentType = "application/x-www-form-urlencoded";
                sw = new StreamWriter(rq.GetRequestStream());
                sw.Write(string.Format(postL, csrf));
                sw.Close();

                Log4cs.Log(Importance.Debug, "Reading response...");
                sr = new StreamReader(rq.GetResponse().GetResponseStream());
                Log4cs.Log(sr.ReadToEnd());

            } catch(Exception ex)
            {
                Log4cs.Log(Importance.Error, "Error TESTing!");
                Log4cs.Log(Importance.Debug, ex.ToString());
            }
        }

        void OnDjangoCommunicatorStatusChanged(object sender, EventArgs e)
        {
            try
            {
                StatusChangeEventArgs ev = (StatusChangeEventArgs)e;
                switch(ev.Operation)
                {
                    case StatusChangeEventArgs.OperationType.CstsDownload:
                        switch(ev.Status)
                        {
                            case StatusChangeEventArgs.StatusType.FinishedOk:
                                Debug("Finish syncing CSTs with ITTC server");
                                RefreshCstsList(m_communicator.Csts);
                                break;
                            case StatusChangeEventArgs.StatusType.StartedOk:
                                Debug("Starting syncing CSTs with ITTC server...");
                                break;
                            case StatusChangeEventArgs.StatusType.Error:
                                Debug("Error syncing CSTs with ITTC server!");
                                break;
                        }
                        break;
                }
            } catch(Exception ex)
            {
                Log4cs.Log(Importance.Error, "!");
                Log4cs.Log(Importance.Debug, ex.ToString());
                
            }
        }

        private void RefreshCstsList(Dictionary<int, string> csts)
        {
            Log4cs.Log(Importance.Debug, "Refreshing list of CSTs from ITTC server. Got {0} CSTs", csts.Count);
            lstCsts.Items.Clear();
            foreach(var kvp in csts)
            {
                lstCsts.Items.Add(kvp);
            }
        }

    }  // END CLASS Form1

}
